package cjj;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@WebServlet("/admin/updateBook")
public class AdminUpdateBookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer adminId = (Integer) request.getSession().getAttribute("adminId");
        if (adminId == null) {
            response.sendRedirect("/admin/login");
            return;
        }

        try {
            Integer bookId = Integer.valueOf(request.getParameter("bookId"));
            String title = request.getParameter("title");
            String author = request.getParameter("author");
            String publisher = request.getParameter("publisher");
            Integer publishYear = Integer.valueOf(request.getParameter("publishYear"));
            String status = request.getParameter("status");

            try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webproject_2025", "root", "root");
                 PreparedStatement stmt = conn.prepareStatement(
                         "UPDATE book SET TITLE=?, AUTHOR=?, PUBLISHER=?, PUBLISH_YEAR=?, STATUS=? WHERE BOOK_ID=?")) {
                stmt.setString(1, title);
                stmt.setString(2, author);
                stmt.setString(3, publisher);
                stmt.setInt(4, publishYear);
                stmt.setString(5, status);
                stmt.setInt(6, bookId);
                int rows = stmt.executeUpdate();

                if (rows > 0) {
                    request.getSession().setAttribute("message", "图书信息更新成功");
                } else {
                    request.getSession().setAttribute("message", "未找到指定图书，更新失败");
                }
            }

            response.sendRedirect("/admin/manageBooks");
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("message", "更新图书失败: " + e.getMessage());
            response.sendRedirect("/admin/manageBooks");
        }
    }
}